package com.justgame.project.cloud.common.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class MapBuilder<K,V> {
    private final Map<K,V> map;

    private final static int DEFAULT_MAP_SIZE = 16;

    public MapBuilder(Map<K, V> map) {
        this.map = map;
    }

    private MapBuilder() {
        this.map = new HashMap<>(DEFAULT_MAP_SIZE);
    }

    private MapBuilder(int mapSize){
        this.map = new HashMap<>(mapSize);
    }

    public static <K,V> MapBuilder<K,V> builder(){
        return new MapBuilder<K,V>();
    }

    public static <K,V> MapBuilder<K,V> builder(int mapSize){
        return new MapBuilder<K,V>(mapSize);
    }

    public MapBuilder<K,V> put(K k,V v){
        map.put(k,v);
        return this;
    }

    public MapBuilder<K,V> putAll(Map<K,V> m){
        map.putAll(m);
        return this;
    }

    public MapBuilder<K,V> remove(K k){
        map.remove(k);
        return this;
    }

    public V get(K key){
        return map.get(key);
    }

    public MapBuilder<K,V> merge(List<Map<K,V>> mapList){
        Optional<Map<K,V>> resultMap = mapList.stream().reduce((m1, m2)->{
            m2.putAll(m1);
            return m2;
        });
        resultMap.ifPresent(map::putAll);
        return this;
    }

    public Map<K,V> build(){
        return map;
    }
}
